﻿using System.Collections.ObjectModel;
using Samples.Radio.Agent;
using Samples.Radio.Data;
using Samples.Radio.Pages.Program;

namespace Samples.Radio.Pages.ProgramList
{
    public class ProgramListPageViewModel:ViewModelBase
    {
        private readonly ObservableCollection<ProgramViewModel> _programs = new ObservableCollection<ProgramViewModel>();
        public ObservableCollection<ProgramViewModel> Programs
        {
            get { return _programs; }
        }

        private ProgramViewModel _SelectedProgram;

        public ProgramViewModel SelectedProgram
        {
            get { return _SelectedProgram; }
            set
            {
                if (SelectedProgram == value) return;
                _SelectedProgram = value;
                RaisePropertyChanged(() => SelectedProgram);
            }
        }
        
       

        public ProgramListPageViewModel(RadioRepository repository, IDispatcher dispatcher, INavigation navigation)
            : base(repository, dispatcher, navigation)
        {
            AddEventWiring(() => Repository.LoadProgramsCompleted += LoadProgramsCompleted,
                () => Repository.LoadProgramsCompleted -= LoadProgramsCompleted);
        }

        private void LoadProgramsCompleted(object sender, ParameterEventArgs<ProgramViewModel[]> e)
        {
            if(e==null || e.Parameter1==null)
            {
                // TODO: Handle errors in loading program data
                return;
            }
            Programs.Replace(e.Parameter1);

           
        }

        public override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs navigationEventArgs, System.Windows.Navigation.NavigationContext context, System.Collections.Generic.IDictionary<string, object> pageState)
        {
            base.OnNavigatedTo(navigationEventArgs, context, pageState);

           Repository.LoadPrograms();
        }

        public void DisplaySelectedProgram()
        {
            if (SelectedProgram == null) return;
            Navigation.Navigate(typeof(ProgramPage), new NavigationParameter("ProgramName", SelectedProgram.ProgramName));
            SelectedProgram = null;
        }
    }
}
